//
//  BBAddBabyRequest.m
//  BabyThermometer
//
//  Created by CaiLei on 10/15/14.
//  Copyright (c) 2014 baohu. All rights reserved.
//

#import "BBAddBabyRequest.h"
#import <ASIFormDataRequest.h>
@implementation BBAddBabyRequestItem
@end

@implementation BBAddBabyRequest {
    void (^_completeBlock)(BBAddBabyRequestItem *retItem, NSError *error);
    ASIFormDataRequest *_uploadImageRequest;
}

- (void)startPostWithBlock:(void(^)(BBAddBabyRequestItem *retItem, NSError *error))aBlock {
    _completeBlock = aBlock;
    
    ASIFormDataRequest *uploadImageRequest = [ ASIFormDataRequest requestWithURL :[NSURL URLWithString:@"http://123.57.38.59:7001/baohu/servlet/addBabyInfo"]];
    self->_uploadImageRequest = uploadImageRequest;
    [uploadImageRequest setStringEncoding:NSUTF8StringEncoding];
    [uploadImageRequest setRequestMethod:@"POST"];
    [uploadImageRequest setPostFormat:ASIMultipartFormDataPostFormat];
    
    [uploadImageRequest setPostValue:self.babayName forKey:@"babyName"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    if (self.birthday) {
        [uploadImageRequest setPostValue:[formatter stringFromDate:self.birthday] forKey:@"birthday"];
    }
    [uploadImageRequest setPostValue:self.sex forKey:@"sex"];
    [uploadImageRequest setPostValue:self.token forKey:@"token"];
    
    NSData *imageData = UIImageJPEGRepresentation(self.photo,100);
    [uploadImageRequest addData:imageData withFileName:@"photo.jpg" andContentType:@"image/jpeg" forKey:@"photo"];
    
    @weakify(self);
    [uploadImageRequest setCompletionBlock:^{
        @strongify(self); if (!self) return;
        NSString *retJson = [[NSString alloc] initWithData:self->_uploadImageRequest.responseData encoding:NSUTF8StringEncoding];
        [self dealWithResponse:retJson];
    }];
    
    [uploadImageRequest setFailedBlock:^{
        @strongify(self); if (!self) return;
        self->_completeBlock(nil, self->_uploadImageRequest.error);
    }];
    [uploadImageRequest startAsynchronous];
}

- (void)dealWithResponse:(NSString *)aJson {
    NSError *error = nil;
    BBAddBabyRequestItem *retItem = [[BBAddBabyRequestItem alloc] initWithString:aJson error:&error];
    if (error) {
        _completeBlock(nil, error);
        return;
    }
    
    if ([retItem.code intValue] == 1201) {
        error = [NSError errorWithDomain:@"添加宝贝" code:1201 userInfo:@{@"msg": @"未找到照片"}];
        _completeBlock(retItem, error);
        return;
    }
    
    _completeBlock(retItem, nil);
}

@end
